<?php

/**
 * 多语言类
 */

namespace variant\ext;

class Lang {

    static protected $langData = array();
    static protected $lang = 'cn';

    /**
     * 初始化当前语言
     */
    static function init() {

        //处理语言配置
        $langConfig = config('LANG');
        $langList = explode(',', $langConfig['LANG_LIST']);
        $langDefault = !empty($langConfig['LANG_DEFAULT']) ? $langConfig['LANG_DEFAULT'] : 'cn';

        if(!$langConfig['LANG_ON']){
            if(!defined('SITE_LANG')) define('SITE_LANG', $langDefault);
            self::$lang = $langDefault;
            return false;
        }

        switch($langConfig['LANG_TYPE']) {
            case 'domain':
                //通过域名获取语言
                $host = $_SERVER['HTTP_HOST'];
                $hostArray = explode('.', $host);
                $lang = $hostArray[0];
                break;
            case 'get':
            default:
            //通过GET获取语言
            $lang = request('get.lang');
            if($lang){
                cookie('lang', $lang, 8760);
            }else{
                $cookieLang = cookie('lang');
                if($cookieLang){
                    $lang = $cookieLang;
                }else{
                    $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 4);
                    foreach($langList as $vo) {
                        if (preg_match("/{$vo}/i", $uaLang)){
                            $lang = $vo;
                        }
                    }
                }
            }
        }

        if(!in_array($lang, $langList)) {
            $lang = $langDefault;
        }

        \variant\core\Config::set('TPL',
            array(
                'TPL_THEME' => config('TPL.TPL_THEME') . '_' . $lang,
            )
        );
        self::$lang = $lang;
        if(!defined('SITE_LANG')) define('SITE_LANG', $lang);
        self::load();
    }

    /**
     * 加载语言包
     */
    static protected function load() {
        //加载公共语言包
        $commonLang = array();
        $file = BASE_PATH . 'app/base/lang/' . self::$lang . '.php';
        if(file_exists($file)){
            $commonLang = require($file);
        }
        //加载APP语言包
        $appLang = array();
        $file = BASE_PATH . 'app/' . APP_NAME . '/lang/' . self::$lang . '.php';
        if(file_exists($file)){
            $appLang = require($file);
        }
        self::$langData = array_merge((array)$commonLang, (array)$appLang);
    }

    /**
     * 获取语言内容
     */
    static public function get($str) {
        $lang = self::$langData;
        if (isset($lang[$str])) {
            return $lang[$str];
        }else{
            return $str;
        }
    }

}